package com.gulimall.cart.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.vo.MemberRespVo;
import com.gulimall.cart.to.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法之前，判断用户的登录状态，并封装传递给controller目标请求
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
    /*
    * 拦截器，当请求过来时，从Session取出值
    * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        Object obj =  session.getAttribute("loginUser");
        String jsonString = JSON.toJSONString(obj);
        MemberRespVo member = JSON.parseObject(jsonString, new TypeReference<MemberRespVo>() {});
        if (member != null) {
            //用户登录
            userInfoTo.setUserId(member.getId());
        }
        //获取所有Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //user-key
                String name = cookie.getName();
                if (name.equals("user-key")) {
                    userInfoTo.setUserKey(cookie.getValue());
                }
            }
        }
        /*如果没有临时用户，则分配临时用户*/
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        //执行目标方法之前
        threadLocal.set(userInfoTo);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Cookie cookie = new Cookie("user-key", threadLocal.get().getUserKey());
        //持续的延长用户过期事件
        cookie.setDomain("gulimall.com");
        cookie.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie);
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

}
